<?php

declare (strict_types=1);

namespace app\api\controller;

use app\api\service\passport\Login as LoginService;
use think\App;
use think\facade\Event;
use think\response\Json;


/**
 * 用户认证模块
 * Class Passport
 * @package app\api\controller
 */
class Passport extends Controller
{
    private LoginService $loginService;
    public function __construct(App $app, LoginService $loginService)
    {
        parent::__construct($app);
        $this->loginService = $loginService;
    }

    /**
     * 登录接口 (需提交手机号、短信验证码、第三方用户信息)
     * @return array|\think\response\Json
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login():Json
    {
        // 执行登录
        $params = $this->postForm();
        $this->validate(
            $params,
            [
                'mobile' => 'require',
                'smsCode' => 'require',
                //'invitation_code|邀请码' => '',
            ]
        );
        $res = $this->loginService->login($params);
        if(!$res){
            return $this->renderError('登录失败');
        }
        // 用户信息
        $userInfo = $this->loginService->getUserInfo();
        $token = $this->loginService->getToken((int)$userInfo['user_id']);
        if(!empty($params['invitation_code'])){
            Event::trigger('InviteHandle', [
                'inviter_id' => decodeInviteCode($params['invitation_code']),
                'invitee_id' => $userInfo['user_id']]
            );
        }
        return $this->renderSuccess([
            'userId' => (int)$userInfo['user_id'],
            'token' => $token,
            'info' => $userInfo,
        ], '登录成功');
    }

    /**
     * 微信小程序快捷登录 (需提交wx.login接口返回的code、微信用户公开信息)
     * 业务流程：判断openid是否存在 -> 存在:  更新用户登录信息 -> 返回userId和token
     */
    public function loginMpWx(): Json
    {
        $params = $this->postForm();
        $this->validate(
            $params,
            [
                'mobile' => 'require',
                'smsCode' => 'require',
                //'invitation_code|邀请码' => '',
            ]
        );
        $res = $this->loginService->loginMpWx($params);
        if (!$res) {
            return $this->renderError('微信登录异常');
        }
        // 获取登录成功后的用户信息
        $userInfo = $this->loginService->getUserInfo();
        $token = $this->loginService->getToken((int)$userInfo['user_id']);
        if(!empty($params['invitation_code'])){
            Event::trigger('InviteHandle', [
                    'inviter_id' => decodeInviteCode($params['invitation_code']),
                    'invitee_id' => $userInfo['user_id']]
            );
        }
        return $this->renderSuccess([
            'userId' => (int)$userInfo['user_id'],
            'token' => $token,
            'info' => $userInfo,

        ], '登录成功');
    }

}